package com.jyxd.web.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jyxd.web.error.JyxdException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 调用第三方接口
     *
     * @param requestBody
     * @param url
     * @return
     */
    public Object requestAppUrl(String requestBody, String url) {
        HttpPost post = new HttpPost(url);
        try {
            logger.info("请求参数为:" + requestBody);
            post.setEntity(new ByteArrayEntity(requestBody.getBytes("UTF-8"), ContentType.APPLICATION_JSON));
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse result = httpClient.execute(post)) {
                logger.debug("获取返回值为：" + JSON.toJSONString(result));
                if (result.getStatusLine().getStatusCode() != 200) {
                    throw new JyxdException("接口请求错误：" + result.getStatusLine().getStatusCode());
                }
                String str = EntityUtils.toString(result.getEntity(), "utf-8");
                JSONObject jsonResult = JSONObject.parseObject(str);
                logger.info("获取到的返回值实体数据为 {}", JSON.toJSONString(jsonResult));
                return JSON.toJSONString(jsonResult);
            }
        } catch (Exception e) {
            throw new JyxdException("接口请求错误");
        }
    }
}
